/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.common.material.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.zx.common.material.entity.TcommonMaterial;
import com.jeesite.modules.zx.common.material.service.TcommonMaterialService;

/**
 * 公共资料Controller
 * @author zpp
 * @version 2020-02-14
 */
@Controller
@RequestMapping(value = "${adminPath}/zx/common/material/tcommonMaterial")
public class TcommonMaterialController extends BaseController {

	@Autowired
	private TcommonMaterialService tcommonMaterialService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public TcommonMaterial get(String id, boolean isNewRecord) {
		return tcommonMaterialService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:view")
	@RequestMapping(value = {"list", ""})
	public String list(TcommonMaterial tcommonMaterial, Model model) {
		model.addAttribute("tcommonMaterial", tcommonMaterial);
		return "modules/zx/common/material/tcommonMaterialList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<TcommonMaterial> listData(TcommonMaterial tcommonMaterial) {
		if (StringUtils.isBlank(tcommonMaterial.getParentCode())) {
			tcommonMaterial.setParentCode(TcommonMaterial.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(tcommonMaterial.getObjName())){
			tcommonMaterial.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcommonMaterial.getObjPicture())){
			tcommonMaterial.setParentCode(null);
		}
		if (tcommonMaterial.getObjType() != null){
			tcommonMaterial.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcommonMaterial.getRemarks())){
			tcommonMaterial.setParentCode(null);
		}
		if (tcommonMaterial.getObjExplain() != null){
			tcommonMaterial.setParentCode(null);
		}
		if (StringUtils.isNotBlank(tcommonMaterial.getObjAnswer())){
			tcommonMaterial.setParentCode(null);
		}
		List<TcommonMaterial> list = tcommonMaterialService.findList(tcommonMaterial);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:view")
	@RequestMapping(value = "form")
	public String form(TcommonMaterial tcommonMaterial, Model model,HttpServletRequest request,HttpServletResponse response) {
		// 创建并初始化下一个节点信息
		tcommonMaterial = createNextNode(tcommonMaterial);
		model.addAttribute("tcommonMaterial", tcommonMaterial);
		String objExplain=request.getParameter("objExplain");
		if(StringUtils.isNotBlank(objExplain)){
			return "modules/zx/common/material/tcommonMaterialForm"+objExplain;
		}
		return "modules/zx/common/material/tcommonMaterialForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public TcommonMaterial createNextNode(TcommonMaterial tcommonMaterial) {
		if (StringUtils.isNotBlank(tcommonMaterial.getParentCode())){
			tcommonMaterial.setParent(tcommonMaterialService.get(tcommonMaterial.getParentCode()));
		}
		if (tcommonMaterial.getIsNewRecord()) {
			TcommonMaterial where = new TcommonMaterial();
			where.setParentCode(tcommonMaterial.getParentCode());
			List<String> stalist=new ArrayList<String>();
			stalist.add("0");
			stalist.add("1");
			stalist.add("2");
			where.getSqlMap().getWhere().disableAutoAddStatusWhere().and("status", QueryType.IN, stalist);
			TcommonMaterial last = tcommonMaterialService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				tcommonMaterial.setTreeSort(last.getTreeSort() + 30);
				tcommonMaterial.setId(IdGen.nextCode(last.getId()));
			}else if (tcommonMaterial.getParent() != null){
				tcommonMaterial.setId(tcommonMaterial.getParent().getId() + "001");
			}
		}
		// 以下设置表单默认数据
		if (tcommonMaterial.getTreeSort() == null){
			tcommonMaterial.setTreeSort(TcommonMaterial.DEFAULT_TREE_SORT);
		}
		return tcommonMaterial;
	}

	/**
	 * 保存公共资料
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TcommonMaterial tcommonMaterial) {
		tcommonMaterialService.save(tcommonMaterial);
		TcommonMaterial parent = tcommonMaterial.getParent();
		tcommonMaterialService.update(parent);
		return renderResult(Global.TRUE, text("保存公共资料成功！"));
	}
	
	/**
	 * 停用公共资料
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(TcommonMaterial tcommonMaterial) {
		TcommonMaterial where = new TcommonMaterial();
		where.setStatus(TcommonMaterial.STATUS_NORMAL);
		where.setParentCodes("," + tcommonMaterial.getId() + ",");
		long count = tcommonMaterialService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该公共资料包含未停用的子公共资料！"));
		}
		tcommonMaterial.setStatus(TcommonMaterial.STATUS_DISABLE);
		tcommonMaterialService.updateStatus(tcommonMaterial);
		return renderResult(Global.TRUE, text("停用公共资料成功"));
	}
	
	/**
	 * 启用公共资料
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(TcommonMaterial tcommonMaterial) {
		tcommonMaterial.setStatus(TcommonMaterial.STATUS_NORMAL);
		tcommonMaterialService.updateStatus(tcommonMaterial);
		return renderResult(Global.TRUE, text("启用公共资料成功"));
	}
	
	/**
	 * 删除公共资料
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TcommonMaterial tcommonMaterial) {
		tcommonMaterialService.delete(tcommonMaterial);
		return renderResult(Global.TRUE, text("删除公共资料成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<TcommonMaterial> list = tcommonMaterialService.findList(new TcommonMaterial());
		for (int i=0; i<list.size(); i++){
			TcommonMaterial e = list.get(i);
			// 过滤非正常的数据
			if (!TcommonMaterial.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getObjName()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("zx:common:material:tcommonMaterial:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(TcommonMaterial tcommonMaterial){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		tcommonMaterialService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}